<?php


namespace App\Http\Controllers\Api;


use App\Http\Controllers\Controller;
use App\Models\Address;
use App\Models\CommodityOrder;
use App\Models\CommodityOrderComment;
use App\Models\CommodityOrderDetail;
use App\Models\CustomerSessionInfo;
use App\Models\GoodsSku;
use App\Service\GroupBuyService;
use App\Service\WechatService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class OrderController extends Controller
{
    //直接购买
    public function buyNow(Request $request)
    {
        $skuId = $request->input('sku_id');
        $num = $request->input('num', 1);
        $addressId = $request->input('address_id');
        $groupBuyType = $request->input('group_buy_type'); // 1开团 2参与拼团
        $groupBuyId = $request->input('group_buy_id'); // 参与拼团id
        $user = $request->user();
        $customer_id = $user['id'];

        DB::beginTransaction();
        try {
            $sn = self::createSn();
            $address = Address::where('id', $addressId)->first();
            $commodity = GoodsSku::with('spu')
                ->find($skuId);

            if ($commodity->spu->commodity_type == 1) {
                $order_status = 3;
            } else {
                $order_status = 1;
            }

            $order = [
                'internal_order_sn' => $sn,
                'order_status' => $order_status,
                'customer_id' => $customer_id,
                'contacts' => $address->contacts,
                'mobile' => $address->phone,
                'full_address' => $address->province . $address->city . $address->area . $address->full_address,
                'internal_payment_sn' => self::createSn(),
                'is_default_address' => $address->is_default
            ];

            $orderId = CommodityOrder::insertGetId($order);


            $orderDetails = [

                'order_id' => $orderId,
                'spu_id' => $commodity->spu->id,
                'spu_name' => $commodity->spu->spu_name,
                'sku_id' => $commodity->id,
                'sku_name' => $commodity->sku_name,
                'shop_id' => $commodity->spu->shop_id,
                'number' => $num,
                'original_price' => $commodity->activity_price,
                'total_price' => $commodity->activity_price * $num,

            ];

            CommodityOrderDetail::insert($orderDetails);
            $updateParams = [
                'order_total_price' => $commodity->activity_price * $num,
                'shop_id' => $commodity->spu->shop_id,
                'commodity_type' => $commodity->spu->commodity_type
            ];
            $isGroupBuy = $commodity->spu->is_group_buy;
            // spu 上必须要为拼团商品
            if ($isGroupBuy) {
                $updateParams['is_group_buy'] = 1;
                // $groupBuyType 1为开团 2为参团
                $result = false;
                if ($groupBuyType == 1) {
                    $result = GroupBuyService::open([$customer_id, $orderId, $commodity->spu->id, 4]); // 发起拼团,数量默认4人
                } else {
                    if ($groupBuyType == 2 && $groupBuyId) {
                        $result = GroupBuyService::joinById($groupBuyId, $customer_id, $orderId);
                    }
                }
                if (!$result) {
                    DB::rollBack();
                    return makeResponse([], '拼团失败～', 500);
                }
            }
            CommodityOrder::where('id', $orderId)->update($updateParams);

            DB::commit();
            return makeResponse(['order_id' => $orderId], '提交成功', 200);
        } catch (\Exception $exception) {
            DB::rollBack();
            return $this->makeResponse([], $exception->getMessage() . ' [LINE]:' . $exception->getLine(), 500);
        }
    }

    public function orderList(Request $request)
    {
        $commodity_type = $request->input('commodity_type');//0-实物，1-虚拟，2-拼团
        $order_status = $request->input('order_status');//订单状态:1-待付款;2-代发货;3-待收货;4-待评价);
        $user = $request->user();
        $customer_id = $user['id'];

        try {
            $order = CommodityOrder::query();
            $order->where('commodity_type', $commodity_type)
                ->where('customer_id', $customer_id)
            ;
            if ($order_status) {
                $order->where('order_status', $order_status);
            }
            $data = $order->with('detail.spu')->orderBy('created_at', 'desc')->paginate(10);
            return makeResponse($data, '查询成功', 200);
        } catch (\Exception $exception) {
            DB::rollBack();
            return $this->makeResponse([], $exception->getMessage() . ' [LINE]:' . $exception->getLine(), 500);
        }
    }


    public function confirmOrder(Request $request)
    {
        $internalPaymentSn = $request->input('internal_payment_sn');
        $orders = CommodityOrder::with('shop', 'detail')->where('internal_payment_sn', $internalPaymentSn)->get();
        $items = [];
        foreach ($orders as $key => $value) {
            $items[$value->shop_id]['shop_name'] = isset($value->shop) ? $value->shop->shop_name : '自营';
            $items[$value->shop_id]['sub'][] = $value->detail;
        }
        return makeResponse($items, 'success', 200);

    }

    public function confirmReceipt(Request $request)
    {
        $internal_order_sn = $request->input('internal_order_sn');
        DB::beginTransaction();
        try {
            $order = CommodityOrder::where('internal_order_sn', $internal_order_sn)->where('order_status', 3)->first();


            if (!$order) {
                return $this->makeResponse([], '订单错误', 404);
            }
            $order->order_status = 4;
            $order->finished_at = date('Y-m-d H:i:s');
            $order->save();
            DB::commit();
            return $this->makeResponse([], '确认成功', 200);
        } catch (\Exception $exception) {
            DB::rollBack();
            return $this->makeResponse([], $exception->getMessage() . ' [LINE]:' . $exception->getLine(), 500);
        }
    }

    public function orderDetails($id)
    {
        $order = CommodityOrder::with('detail.spu')->find($id);
        return $this->makeResponse($order, '查询成功', 200);

    }

    public function commentOrder(Request $request)
    {

        $a = [
            'order_id' => 98,
            'comments' => [
                [
                    'order_detail_id' => 861,
//            'order_id' => 98,
                    'content' => '好评5',
                    'fraction' => '5',
                    'images' => ['https://imgcdn.tuogouchebao.com/property/xiangqingtutuo.png', 'https://imgcdn.tuogouchebao.com/property/xiangqingtutuo.png'],
                ], [
                    'order_detail_id' => 862,
//            'order_id' => 98,
                    'content' => '好评4',
                    'fraction' => '4',
                    'images' => ['https://imgcdn.tuogouchebao.com/property/xiangqingtutuo.png', 'https://imgcdn.tuogouchebao.com/property/xiangqingtutuo.png'],


                ]
            ]
        ];

//        dd(str_replace("\\/", "/", json_encode($a, JSON_UNESCAPED_UNICODE)));

        DB::beginTransaction();
        try {

            $comments = json_decode($request->input('comments', []), true);
            $order_id = $request->input('order_id');
            $user = $request->user();
            $customer_id = $user['id'];
            $data = [];
            foreach ($comments as $v) {
                $data[] = [
                    'order_detail_id' => $v['order_detail_id'],
                    'order_id' => $order_id,
                    'content' => $v['content'],
                    'spu_id' => $v['spu_id'],
                    'sku_id' => $v['sku_id'],
                    'fraction' => $v['fraction'],
                    'images' => json_encode($v['images']),
                    'customer_id' => $customer_id
                ];
            }

            CommodityOrderComment::insert($data);
            CommodityOrder::where('id', $order_id)->update(['order_status' => 5]);
            DB::commit();
            return $this->makeResponse([], '评价成功', 200);
        } catch (\Exception $exception) {
            DB::rollBack();
            return $this->makeResponse([], $exception->getMessage() . ' [LINE]:' . $exception->getLine(), 500);
        }
    }


    public function moreComment(Request $request)
    {
        $spuId = $request->input('spu_id');

        $comment = CommodityOrderComment::
        with(['customer' => function ($query) {
            $query->select('id', 'nick_name', 'avatar_url');
        }])->where('spu_id', $spuId)->orderBy('created_at', 'desc')->paginate(10);
        return $this->makeResponse($comment, '查询成功', 200);
    }

    public function myComment(Request $request)
    {
        $user = $request->user();
        $customer_id = $user['id'];

        $customer = CustomerSessionInfo::select('id', 'nick_name', 'avatar_url')->find(10);

        $comment = CommodityOrderComment::with('spu')->where('customer_id', 10)->paginate(10);
        return $this->makeResponse(
            ['customer' => $customer, 'comment' => $comment]
            , '查询成功', 200);
    }

    public function myGroupBuyList()
    {


    }

    public function wechatPayment(Request $request)
    {
        $internalPaymentSn = $request->input('internal_payment_sn');
        $orderId = $request->input('order_id');
        $user = $request->user();


        if (isset($orderId)) {
            $orders = CommodityOrder::where('id', $orderId)->first();
            $total = $orders->order_total_price;
            $internalPaymentSn = $orders->internal_payment_sn;
        } else {
            $orders = CommodityOrder::where('internal_payment_sn', $internalPaymentSn)->get();
            $total = 0;
            foreach ($orders as $key => $value) {
                $total += sprintf('%.2f',$value->order_total_price);
            }
        }
        $notifyUrl = "http://nonghuapi.quanyubao.cn/api/payment/shoppingCallBack";

        $wechatService = new WechatService();
        $result = $wechatService->payment(['农户商城', $internalPaymentSn, $total * 100, $notifyUrl, $user['open_id']]);
        return makeResponse($result, 'success', 200);
    }
}